package com.bml.architect.spring.convert.spring;

import com.bml.architect.spring.service.User;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.util.Collections;
import java.util.Random;
import java.util.Set;

/**
 * spring 提供的类型转换
 */
public class StringToUserConvert implements ConditionalGenericConverter {

    /**
     *校验是否匹配，是否需要进行转换
     * @param typeDescriptor 原类型
     * @param typeDescriptor1 目标类型
     * @return
     */

    @Override
    public boolean matches(TypeDescriptor typeDescriptor, TypeDescriptor typeDescriptor1) {
        return typeDescriptor.getType().equals(String.class) && typeDescriptor1.getType().equals(User.class);
    }

    /**
     * 将要转换的类型都放到set集合里面返回，如果有多个
     * new ConvertiblePair(String.class,User.class) 原类型 目标类型
     * new ConvertiblePair(String.class,User1.class)
     * new ConvertiblePair(String.class,User2.class)
     * @return
     */
    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class,User.class));
    }

    /**
     * 转换的自定义逻辑
     * @param o
     * @param typeDescriptor
     * @param typeDescriptor1
     * @return
     */

    @Override
    public Object convert(Object o, TypeDescriptor typeDescriptor, TypeDescriptor typeDescriptor1) {
        User user = new User();
        user.setId(new Random().nextInt(100));
        user.setName((String) o);
        return user;
    }
}
